﻿using Autofac;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Lails.Server
{
    public class ActionForAppIdFilter : IActionFilter
    {
        const string appIdName = "appid";
        public ActionForAppIdFilter()
        {
        }

        public bool AllowMultiple
        {
            get
            {
                return true;
            }
        }

        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            var context = actionContext;
            if (context.Request.Headers != null && context.Request.Headers.ToDictionary(k => k.Key, v => v.Value).ContainsKey(appIdName))
            {

                var appid = context.Request.Headers.ToDictionary(k => k.Key, v => v.Value)[appIdName];

               

                //AutofacConfig.Builder.RegisterType<ApiController>().OnActivating(e => e.Parameters  .a..Instance.D = e.Context.Resolve<ClassD>());
                //AutofacConfig.Builder.RegisterType(typeof(ApiController)).SingleInstance();
            }

            return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                //Content = new StringContent(baseException.Message),
                //ReasonPhrase = "Critical Error"
            });
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        //public void OnActionExecuting(ActionExecutingContext context)
        //{
        //    var parameters = context.ActionDescriptor.Parameters;
        //    foreach (var parameter in parameters)
        //    {
        //        ControllerParameterDescriptor pdes = parameter as ControllerParameterDescriptor;
        //        var customAttributes = pdes.ParameterInfo.CustomAttributes;
        //        if (customAttributes != null)
        //        {
        //            if (customAttributes.Where(n => n.AttributeType.Equals(typeof(EncryptParamAttribute))).Count() > 0)
        //            {
        //                object data;
        //                if (context.ActionArguments.TryGetValue(pdes.Name, out data))
        //                {
        //                    data = data + "Injected!";
        //                    context.ActionArguments["value"] = data;
        //                }
        //            }
        //        }
        //    }
        //}
    }
}
